import store from '@/store'
import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL
})
const router = useRouter()
request.interceptors.request.use(
  config => {
    // 统一设置用户身份 Token
    const { user } = store.state
    if (user && user.token) {
      config.headers.Authorization = `Bearer ${user.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 统一处理响应错误，例如 token 无效、服务端异常等
    const { status } = response
    if (!status || status === 200) {
      return response
    }
    let isRefreshing = false
    if (status === 410000) {
      if (isRefreshing) return Promise.reject(response)
      isRefreshing = true
      ElMessageBox.confirm('您的登录已过期，您可以取消停留在此页面，或确认重新登录', '登录过期', {
        confirmButtonText: '确认',
        cancelButtonText: '取消'
      }).then(() => {
      // 清除本地过期的登录状态
        store.commit('setUser', null)
        // 跳转到登录页面
        router.push({
          name: 'login',
          query: {
            redirect: router.currentRoute.value.fullPath
          }
        })
      // 抛出异常
      }).finally(() => {
        isRefreshing = false
      })

      // 在内部消化掉这个业务异常
      return Promise.reject(response)
    }
    ElMessage({
      type: 'error',
      message: response.data.message,
      duration: 5000
    })
    return Promise.reject(response)
  },
  err => {
    ElMessage({
      type: 'error',
      message: err.message,
      duration: 5000
    })
    return Promise.reject(err)
  }
)

export default <T=any>(config:AxiosRequestConfig) => {
  return request(config).then((res) => {
    return (res.data.data || res.data) as T
  })
}
